const { Pool } = require('pg');
require('dotenv').config();

const pool = new Pool({
  host: process.env.DB_HOST,
  port: process.env.DB_PORT,
  user: process.env.DB_USER,
  password: process.env.DB_PASSWORD,
  database: process.env.DB_DATABASE,
  max: process.env.DB_MAX_CONNECTION,
  idleTimeoutMillis: process.env.DB_IDLE_TIMEOUT, // 空闲连接超时
  connectionTimeoutMillis: process.env.DB_CONNECTION_TIMEOUT, // 连接超时
  // 生产环境建议添加SSL配置
  // ssl: { rejectUnauthorized: false }
});

// 测试连接
pool.query('SELECT NOW()', (err) => {
  if (err) {
    console.error('Database connection failed:', err);
  } else {
    console.log('Successfully connected to database');
  }
});

module.exports = pool;